/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.ohos.core;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Method;

import io.sentry.IHub;
import io.sentry.Integration;
import io.sentry.SentryLevel;
import io.sentry.SentryOptions;
import io.sentry.util.Objects;

/**
 * NdkIntegration
 *
 * @since 2021-06-01
 */
public final class NdkIntegration implements Integration, Closeable {
    /**
     * SENTRY_NDK_CLASS_NAME
     */
    public static final String SENTRY_NDK_CLASS_NAME = "io.sentry.ohos.ndk.SentryNdk";

    private final @Nullable Class<?> sentryNdkClass;

    private @Nullable SentryOhosOptions sentryOhosOptions;

    /**
     * NdkIntegration
     *
     * @param sentryNdkClass Class<?>
     */
    public NdkIntegration(final @Nullable Class<?> sentryNdkClass) {
        this.sentryNdkClass = sentryNdkClass;
    }

    @Override
    public void register(@NotNull IHub hub,@NotNull SentryOptions options) {
        Objects.requireNonNull(hub, "Hub is required");
        this.sentryOhosOptions =
            Objects.requireNonNull(
                (options instanceof SentryOhosOptions) ? (SentryOhosOptions) options : null,
                "SentryOhosOptions is required");

        final boolean isEnabled = this.sentryOhosOptions.isEnableNdk();
        this.sentryOhosOptions.getLogger().log(SentryLevel.DEBUG, "NdkIntegration enabled: %s", isEnabled);

        // Note: `hub` isn't used here because the NDK integration writes files to disk which are picked
        // up by another integration (EnvelopeFileObserverIntegration).
        if (isEnabled && sentryNdkClass != null) {
            final String cachedDir = this.sentryOhosOptions.getCacheDirPath();
            if (cachedDir == null || cachedDir.isEmpty()) {
                this.sentryOhosOptions.getLogger().log(SentryLevel.ERROR, "No cache dir path is defined in options.");
                this.sentryOhosOptions.setEnableNdk(false);
                return;
            }

            try {
                final Method method = sentryNdkClass.getMethod("init", SentryOhosOptions.class);
                final Object[] args = new Object[1];
                args[0] = this.sentryOhosOptions;
                method.invoke(null, args);

                this.sentryOhosOptions.getLogger().log(SentryLevel.DEBUG, "NdkIntegration installed.");
            } catch (NoSuchMethodException e) {
                this.sentryOhosOptions.setEnableNdk(false);
                this.sentryOhosOptions
                    .getLogger()
                    .log(SentryLevel.ERROR, "Failed to invoke the SentryNdk.init method.", e);
            } catch (Throwable e) {
                this.sentryOhosOptions.setEnableNdk(false);
                this.sentryOhosOptions.getLogger().log(SentryLevel.ERROR, "Failed to initialize SentryNdk.", e);
            }
        } else {
            this.sentryOhosOptions.setEnableNdk(false);
        }
    }

    @TestOnly
    @Nullable
    Class<?> getSentryNdkClass() {
        return sentryNdkClass;
    }

    @Override
    public void close() throws IOException {
        if (sentryOhosOptions != null && sentryOhosOptions.isEnableNdk() && sentryNdkClass != null) {
            try {
                final Method method = sentryNdkClass.getMethod("close");
                method.invoke(null, new Object[0]);

                sentryOhosOptions.getLogger().log(SentryLevel.DEBUG, "NdkIntegration removed.");
            } catch (NoSuchMethodException e) {
                sentryOhosOptions
                    .getLogger()
                    .log(SentryLevel.ERROR, "Failed to invoke the SentryNdk.close method.", e);
            } catch (Throwable e) {
                sentryOhosOptions.getLogger().log(SentryLevel.ERROR, "Failed to close SentryNdk.", e);
            } finally {
                this.sentryOhosOptions.setEnableNdk(false);
            }
        }
    }
}
